<template>
	<view>
		<view class="block" v-if="!show_input">

		</view>
		<view class="inputbody" v-if="show_input">
			<view class="input-box">
				<input type="text" v-model="recommend" placeholder="请输入邀请码">
			</view>

			<view class="btn" @tap="bind_tj">
				绑定
			</view>
		</view>
		<view class="qrbox" v-else>

			<view class="codebox" @click="copy">我的邀请码：{{code}}
				<image src="/static/img/user/copy_w.png" mode="widthFix"></image>
			</view>
			<view class="QR">
				<view class="imgbox">
					<uqrcode ref="uqrcode" canvas-id="qrcode" :size="100" :value="link" @longtap="save"></uqrcode>
				</view>
			</view>

			<view class="btn" @tap="printscreen" v-if="!show_canvas">
				{{tis}}
			</view>
			<view class="canvasbox" v-if="show_canvas">
				<image v-if="saveimg_url!=''" :src="saveimg_url" mode=""></image>
				<canvas canvas-id="mycanvas" id="mycanvas" style="width: 100%;height: 100%"></canvas>
				<!-- #ifdef APP -->
				<button @click="appSaveImg">保存图片</button>
				<!-- #endif -->
			</view>
			<!-- <view class="logo">
				<image mode="widthFix" src="../../../static/img/qrlogo.png"></image>
			</view> -->
		</view>
	</view>
</template>

<script>
	import {
		UserQrcode,
		BindRecommend
	} from "@/api/user.js"
	export default {
		data() {
			return {
				tis: "保存到相册",
				showBtn: false,
				qrimg: '',
				code: '',
				show_input: false,
				recommend: '',
				canvasWidth: 300,
				canvasHeight: 900,
				show_canvas: false,
				saveimg_url: '',
				link: '',
				code_url: ''
			};
		},
		async onReady() {
			let res = await UserQrcode()
			if (res.status == 1) {
				this.qrimg = res.data.qr
				this.code = res.data.code
				this.link = getApp().globalData.data.websiteUrl + `pages/login/register?recommend=${this.code}`
				this.show_input = false
			} else {
				this.show_input = true
			}
			let info = uni.getWindowInfo()
			this.canvasWidth = info.windowWidth * .8
			this.canvasHeight = info.windowHeight * .77
		},
		onLoad() {
			// #ifdef APP-PLUS
			this.showBtn = true;
			// #endif
		},
		methods: {
			appSaveImg() {
				var that = this
				uni.saveImageToPhotosAlbum({
					filePath: that.saveimg_url,
					success(res) {
						uni.$showMsg('保存成功')
					},
					fail(err) {
						uni.$showMsg('保存失败')
					}
				})
			},
			saveImg() {
				var that = this
				uni.canvasToTempFilePath({
					canvasId: 'mycanvas',
					success: function(res) {
						that.saveimg_url = res.tempFilePath
						uni.showToast({
							title: '绘制成功'
						});
					},
					fail: function() {
						uni.showToast({
							title: '绘制失败'
						});
					},
					complete: function() {
						uni.hideToast();
					}
				});
				return
				uni.getSetting({
					success(res) {
						if (Object.keys(res.authSetting).length > 0) {
							//判断是否有相册权限
							if (res.authSetting['scope.writePhotosAlbum'] == undefined) {
								//打开设置权限
								uni.authorize({
									scope: "scope.writePhotosAlbum",
									success: (res) => {
										uni.canvasToTempFilePath({
											canvasId: 'myCanvas',
											quality: 1,
											complete: (res) => {
												uni.saveImageToPhotosAlbum({
													filePath: res.tempFilePath,
													success(res) {
														uni.showToast({
															title: '已保存到相册',
															icon: 'success',
															duration: 2000
														})
														setTimeout(() => {
															that.isShow =
																false
														}, 2000)
													}
												})
											}
										}, that);
									}
								})

							} else {
								uni.canvasToTempFilePath({
									canvasId: 'myCanvas',
									quality: 1,
									complete: (res) => {
										uni.saveImageToPhotosAlbum({
											filePath: res.tempFilePath,
											success(res) {
												uni.showToast({
													title: '已保存到相册',
													icon: 'success',
													duration: 2000
												})
												setTimeout(() => {
													that.isShow =
														false
												}, 2000)
											}
										})
									}
								}, that);
							}
						} else {
							return
						}
					}
				})
			},
			onCanvas() {
				var _this = this
				let url = getApp().globalData.data.websiteUrl + _this.qrimg
				uni.showLoading({
					title: '海报生成中'
				})
				const ctx = uni.createCanvasContext('mycanvas', _this);
				// 设置 canvas 背景色
				ctx.setFillStyle('#FFFFFF');
				ctx.fillRect(0, 0, _this.canvasWidth, _this.canvasHeight);
				ctx.setFillStyle('#fff');
				// 背景图片
				ctx.drawImage('/static/img/qrcg.jpg', 0, 0, _this.canvasWidth, _this.canvasHeight);
				ctx.setFontSize(14);
				ctx.setTextAlign('center');
				ctx.fillText('我的邀请码 :', _this.canvasWidth * .8, 50);
				ctx.fillText(_this.code, _this.canvasWidth * .8, 80);
				// 左边标题
				ctx.setTextAlign('left')
				ctx.setFontSize(16)
				// _this.writeTextOnCanvas(ctx, 30, 21, '我的邀请码111', 50, 350);
				// 设置虚线
				ctx.setStrokeStyle('#333333');
				ctx.setLineDash([5, 10], 2);
				ctx.beginPath();
				ctx.moveTo(220, 340);
				ctx.lineTo(220, 420);
				ctx.stroke();
				// 二维码
				ctx.drawImage(_this.code_url, 10, _this.canvasHeight * 0.78, 80, 80);
				ctx.draw();
				setTimeout(() => {
					_this.saveImg()
					uni.hideLoading()
				}, 1000)
				// 延迟后渲染至canvas上
				// let pic = await _this.setTime(ctx)
				// _this.$emit('success', pic);
				// _this.qr_code = '';
			},
			bind_tj() {
				if (this.recommend == '') {
					uni.showToast({
						title: '请输入邀请码',
						icon: "none"
					})
					return false
				}
				BindRecommend({
					code: this.recommend
				}).then(res => {
					uni.showToast({
						title: res.message,
						icon: "none"
					})
					if (res.status == 1) {
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/tabBar/user/user'
							})
						}, 1000)
					}
				})
			},
			copy() {
				if (this.code) {
					uni.setClipboardData({
						data: this.code,
						success: (res) => {
							uni.showToast({
								title: '复制成功',
								icon: "none"
							})
						}
					})
				}
			},
			UserQrcode() {
				UserQrcode().then(res => {


				})
			},
			// 截图，调用webview、Bitmap方法
			printscreen() {
				var that = this
				uni.canvasToTempFilePath({
					canvasId: 'qrcode',
					success: function(res) {
						that.code_url = res.tempFilePath
						that.show_canvas = true
						setTimeout(() => {
							that.onCanvas()
						})
					}
				});

				return
				this.tis = "正在保存"
				let ws = this.$mp.page.$getAppWebview();
				let bitmap = new plus.nativeObj.Bitmap();
				this.showBtn = false;
				this.$nextTick(function() {
					setTimeout(() => {
						ws.draw(bitmap, (e) => {
							this.showBtn = true;
							bitmap.save("_doc/Qr.jpg", {
								overwrite: true,
								quality: 100
							}, (i) => {
								plus.gallery.save(i.target, (e) => {
									uni.showToast({
										title: '保存成功'
									})
									this.tis = "保存到相册"
									bitmap.clear(); //销毁
								}, (e) => {
									bitmap.clear(); //销毁
								});
							}, (e) => {
								console.log('保存图片失败：' + JSON.stringify(e));
							});
						}, (e) => {
							console.log('bitmap绘制图片失败：' + JSON.stringify(e));
						});
					}, 200)
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		width: 100vw;
		height: 100%;
		min-height: 100vh;
		/* #ifdef H5 */
		min-height: calc(100vh - 44px);
		/* #endif */
		background: url(/static/img/qrcg.jpg) no-repeat;
		background-size: 100% 100%;
	}



	.canvasbox {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 80%;
		height: 70%;
		opacity: 1;

		&.hide {
			opacity: 0;
		}

		canvas {
			width: 100%;
			height: 100%;
			opacity: 0;
		}

		image {
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			box-shadow: 0 0 10px #000;
			border-radius: 8px;
			z-index: 999;
		}

		button {
			background: #8980fd;
			color: #fff;
			font-size: 14px;
			margin-top: 20px;
		}
	}

	.inputbody {
		position: absolute;
		right: 0;
	}

	.block {
		width: 100%;
		height: 30vh;
		background-color: transparent;
		display: flex;
		justify-content: center;

	}

	.input-box {
		margin: 0 auto;
		margin-top: 10px;
		width: 94%;
		box-sizing: border-box;

		input {
			background: #fff;
			height: 40px;
			border-radius: 5px;
			padding: 0 10px;
		}
	}


	.codebox {
		text-align: center;
		width: 35%;
		font-weight: bold;
		display: flex;
		align-items: center;
		justify-content: center;
		position: absolute;
		top: 7vh;
		color: #fff;
		right: 4vw;

		image {
			width: 20%;
			margin-left: 8px;
		}
	}

	.QR {
		// width: 60vw;
		// height: 60vw;
		margin: 0 auto;
		margin-top: 30px;
		background-color: transparent;
		display: flex;
		justify-content: center;
		align-items: center;

		.imgbox {
			width: 28vw;
			height: 28vw;
			position: absolute;
			bottom: 8vh;
			left: 3vh;
		}
	}

	.title {
		width: 100%;
		margin-top: 50upx;
		display: flex;
		justify-content: center;
		font-size: 36upx;
		color: #fff;
	}

	.btn {
		position: relative;
		z-index: 9999;
		width: 50%;
		height: 80upx;
		border-radius: 80upx;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 0 20upx;
		margin: 0 auto;
		margin-top: 10px;
		background-color: rgba(255, 255, 255, .8);
	}

	.logo {
		width: 100%;
		display: flex;
		justify-content: center;
		position: absolute;
		bottom: 25upx;

		image {
			width: 39.6%;
		}

	}
</style>